package woaini.wind.bot.chat.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.BoundedPriorityQueue;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.plexpt.chatgpt.ChatGPT;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import woaini.wind.bot.chat.AbstractChatter;
import woaini.wind.bot.chat.config.ChatterBaseConfig;
import woaini.wind.bot.chat.config.OpenAiChatterConfig;
import woaini.wind.bot.chat.dto.ChatMessage;
import woaini.wind.bot.chat.stream.WindChatStream;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;

/**
 * @see GptChatter
 * @author yefeng {@date 2024-09-03 18:12:34}
 */
@Slf4j
@Component
@EnableConfigurationProperties(OpenAiChatterConfig.class)
public class GptChatter extends AbstractChatter {

  private final ChatGPT chatClient;
  public static final String BALANCE_URL = "/v1/query/balance";

  public GptChatter(OpenAiChatterConfig openAiChatterConfig) {
    super(openAiChatterConfig);
    chatClient =
        ChatGPT.builder()
            .apiKey(openAiChatterConfig.getApiKey())
            .apiHost(openAiChatterConfig.getHost())
            .build()
            .init();
  }

  @Override
  public String handlerChat(String userId,String userName, List<ChatMessage> messages) {

    List<Message> messageList = BeanUtil.copyToList(messages, Message.class);
    ChatCompletionResponse chatCompletionResponse = chatClient.chatCompletion(messageList);
    log.info(JSONObject.toJSONString(chatCompletionResponse));
    return chatCompletionResponse.getChoices().get(0).getMessage().getContent();
  }

  @Override
  public void streamHandlerChat(BoundedPriorityQueue<ChatMessage> cacheMessageQueue, SubmissionPublisher<String> publisher, String userId, String userName, List<ChatMessage> messages) {

  }

  @Override
  public String useInfo() {


    OpenAiChatterConfig aiChatterConfig = (OpenAiChatterConfig) this.chatterBaseConfig;

    String body =
        HttpRequest.post(aiChatterConfig + BALANCE_URL)
            .header("Authorization", aiChatterConfig.getApiKey())
            .execute()
            .body();

    JSONObject jsonObject = JSONObject.parseObject(body);
    BigDecimal total = jsonObject.getBigDecimal("balanceTotal");
    BigDecimal used = jsonObject.getBigDecimal("balanceUsed");
    //计算剩余百分比
    double percent = used.divide(total, 4, BigDecimal.ROUND_HALF_UP).doubleValue();

    return  STR."剩余:\{ (1 - percent) * 100}%,总额:\{total},使用:\{used}";
  }
}
